package com.lipy.java8study.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description copy from dubbo EagerThreadPoolExecutor  线程池 创建到最大线程数 后再放到队列中
 * @Date 2020/11/25 10:32
 * @Author lipye  by lipye
 */
public class EagerThreadPoolExecutor extends ThreadPoolExecutor {
    private final AtomicInteger submittedTaskCount = new AtomicInteger(0);

    public EagerThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, TaskQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    public int getSubmittedTaskCount() {
        return this.submittedTaskCount.get();
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        this.submittedTaskCount.decrementAndGet();
    }

    @Override
    public void execute(Runnable command) {
        if (command == null) {
            throw new NullPointerException();
        } else {
            this.submittedTaskCount.incrementAndGet();

            try {
                super.execute(command);
            } catch (RejectedExecutionException var6) {
                TaskQueue queue = (TaskQueue)super.getQueue();

                try {
                    if (!queue.retryOffer(command, 0L, TimeUnit.MILLISECONDS)) {
                        this.submittedTaskCount.decrementAndGet();
                        throw new RejectedExecutionException("Queue capacity is full.");
                    }
                } catch (InterruptedException var5) {
                    this.submittedTaskCount.decrementAndGet();
                    throw new RejectedExecutionException(var5);
                }
            } catch (Throwable var7) {
                this.submittedTaskCount.decrementAndGet();
            }

        }
    }
}